<template>
    <a-drawer
      :visible="localVisible"
      title="资源内容"
      :width="600"
      @close="handleClose"
    >
      <div v-if="resource">
        <div style="display: flex; justify-content: space-between; align-items: center;">
        <h3>{{ resource.title }}</h3>
          <a-button danger ghost @click="confirmDeleteResource">
            删除资源
          </a-button>
                </div>
        <p>{{ resource.description }}</p>
        <p><strong>资源类型:</strong> {{ getResourceTypeName(resource.type) }}</p>

        <div v-if="selectedFile">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
              <a-button type="link" @click="$emit('deselect-file')">返回文件列表</a-button>
              <div>
                <a-button 
                type="primary" 
                @click="showVersionHistory = true; fetchFileVersions()"
                style="margin-right: 8px;"
              >
                <a-icon type="history" /> 版本历史
              </a-button>
              <a-button type="primary" @click="goToChat" style="margin-right: 8px;">
                发送给小助手
              </a-button>
              <a-button danger ghost @click="confirmDeleteFile">
                删除文件
              </a-button>
            </div>
          </div>

          <a-tabs v-model:activeKey="fileActionTab">
            <a-tab-pane key="preview" tab="预览">
                <h4>文件预览: {{ selectedFile.name }}</h4>
                <div v-if="selectedFile.content" style="margin-top: 16px; padding: 16px; background: #f5f5f5; border-radius: 4px;">
                  {{ selectedFile.content }}
              </div>
              <!-- 获取选择文件的URL利用kkfileview来预览 -->
                <FilePreview :file-url="selectedFile?.url"/>
            </a-tab-pane>

          <a-tab-pane key="edit" tab="编辑">
              <a-spin :spinning="loading">
                <div v-if="formData">
                  <json-editor
                    :data="formData"
                    @update:data="formData = $event"
                  />
                <div style="text-align: right; margin-top: 16px;">
                  <a-button type="primary" @click="handleSave">保存</a-button>
                </div>
              </div>
              <div v-else-if="!loading" style="text-align: center; padding: 20px;">
                <a-empty description="无法加载文件内容" />
              </div>
            </a-spin>
          </a-tab-pane>
        </a-tabs>
      </div>

      <div v-else>
        <a-row :gutter="[16, 16]" style="margin-top: 20px;">
          <a-col :span="6" v-for="file in filteredFiles" :key="file.name">
            <a-card hoverable style="text-align: center; padding: 10px;" @click="$emit('select-file', file)">
              <template #cover>
                <div class="resource-icon">
                  <component :is="getIconComponent(resource.type)" style="font-size: 40px;" />
                </div>
              </template>
              <p style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 100%;">{{ file.name }}</p>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card hoverable @click="$emit('show-add-file')">
              <div style="font-size: 30px; margin-bottom: 10px;">
                <a-icon type="plus" style="font-size: 40px;"/>
              </div>
              <a-card-meta title="添加新文件" description="点击添加新的文件"/>
            </a-card>
          </a-col>
        </a-row>
      </div>
    </div>
  </a-drawer>
  <a-modal
    v-model:visible="showVersionHistory"
    title="文件版本历史"
    width="800px"
    :footer="null"
  >
    <a-table
      :columns="versionColumns"
      :dataSource="fileVersions"
      :loading="versionLoading"
      rowKey="version"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'created_at'">
          {{ formatDate(record.created_at) }}
        </template>
        <template v-if="column.dataIndex === 'actions'">
          <a-button type="link" @click="restoreVersion(record)">恢复</a-button>
        </template>
      </template>
    </a-table>
  </a-modal>
</template>

<script>
import axios from 'axios';
import FilePreview from "../FilePreview.vue";
import JsonEditor from './JsonEditor.vue';
import { FileOutlined, FileTextOutlined, CalendarOutlined, VideoCameraOutlined } from '@ant-design/icons-vue';
import { Modal } from 'ant-design-vue';
export default {
  name: "ResourcePanel",
  components: { FilePreview, JsonEditor },
  props: {
    visible: { type: Boolean, default: false },
    resource: { type: Object, default: null },
    files: { type: Array, default: () => [] },
    selectedFile: { type: Object, default: null }
  },
  data() {
    return {
      localVisible: this.visible,
      fileActionTab: "preview",
      formData: null,
      loading: false,
      analyzing: false,
      currentUser: 'user_' + Math.random().toString(36).substr(2, 9),
      versionColumns: [
        {
          title: '版本号',
          dataIndex: 'version',
          key: 'version'
        },
        {
          title: '文件名',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '类型',
          dataIndex: 'type',
          key: 'type',
          customRender: ({ text }) => this.getResourceTypeName(text)
        },
        {
          title: '创建时间',
          dataIndex: 'created_at',
          key: 'created_at'
        },
        {
          title: '操作',
          dataIndex: 'actions',
          key: 'actions'
        }
      ],
      showVersionHistory: false,
      fileVersions: [],
      versionLoading: false,
      difyConfig: {
        baseUrl: 'http://localhost/v1',
        apiKey: 'app-ijcvqqiPoXQs3RRyyYzLDOg1',
        endpoints: {
          chat: '/chat-messages'
        }
      },
      fileIcons: {
        transcript: 'file-text',
        video: 'video-camera',
        audio: 'sound',
        image: 'picture',
        document: 'file-word',
        default: 'file'
      },
      resourceTypes: {
        ppt: 'PPT课件',
        transcript: '讲稿',
        plan: '教案',
        media: '多媒体资源'
      }
    };
  },
  computed: {
    filteredFiles() {
      if (!this.resource || !this.resource.id) return [];

      return this.files.filter(file =>
        file.resource === this.resource.id &&
        (this.resource.type ? file.type === this.resource.type : true)
      );
    }
  },
  watch: {
    visible(newVal) {
      this.localVisible = newVal;
    },
    localVisible(newVal) {
      this.$emit('update:visible', newVal);
    },
    selectedFile: {
      immediate: true,
      handler(newVal) {
        if (newVal && newVal.json_data) {
          this.loadJsonData();
        } else {
          this.formData = null;
        }
      }
    }
  },
  methods: {
    handleSave() {
      if (this.formData) {
        console.log('保存的数据:', this.formData);
        this.$emit('save-teaching-plan', this.formData);
        this.$message.success('保存成功');
      }
    },
    loadJsonData() {
      this.loading = true;
      try {
        const jsonData = typeof this.selectedFile.json_data === 'string'
          ? JSON.parse(this.selectedFile.json_data)
          : this.selectedFile.json_data;
        this.formData = jsonData;
      } catch (error) {
        console.error('解析JSON数据失败:', error);
        this.$message.error('解析JSON数据失败: ' + error.message);
      } finally {
        this.loading = false;
      }
    },
    async fetchFileVersions() {
      this.versionLoading = true;
      try {
        const response = await axios.get(`/api/files/${this.selectedFile.id}/versions`, {
          baseURL: 'http://localhost:8000', // Set correct base URL
          headers: {
            'Accept': 'application/json'
          }
        });
        this.fileVersions = Array.isArray(response.data) 
        ? response.data.map(version => ({
            ...version,
            name: this.selectedFile.name,  // Add file name
            type: this.selectedFile.type,    // Add file type
          }))
        : [];
        // Add debug logging
        console.log('Raw response:', response);
        console.log('Response headers:', response.headers);
        console.log('Response data type:', typeof response.data);

        // Check if response is HTML
        if (typeof response.data === 'string' && response.data.trim().startsWith('<!DOCTYPE html>')) {
          throw new Error('Server returned HTML instead of JSON. Check API endpoint.');
        }

        this.fileVersions = Array.isArray(response.data) ? response.data : [];
      } catch (error) {
        console.error('获取版本历史失败:', {
          error: error.message,
          config: error.config,
          response: error.response
        });
        this.$message.error('获取版本历史失败: ' + (error.response?.data?.message || error.message));
        this.fileVersions = [];
      } finally {
        this.versionLoading = false;
      }
    },
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleString(); // or use more specific formatting if needed
    },
    restoreVersion(version) {
      Modal.confirm({
        title: '确认恢复版本',
        content: `确定要恢复到此版本 (${version.version}) 吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk: async () => {
        try {
          await this.$emit('restore-version', { 
            version_id: version.id  // Ensure this matches backend expectation
          });
          this.showVersionHistory = false;
        } catch (error) {
          this.$message.error('恢复版本失败');
        }
      }
    });
    },
    getFileIcon(fileType) {
      return this.fileIcons[fileType] || this.fileIcons.default;
    },
    handleClose() {
      this.localVisible = false;
      this.$emit("close");
    },
    getIconComponent(type) {
      const iconMap = {
        ppt: FileOutlined,
        transcript: FileTextOutlined,
        plan: CalendarOutlined,
        media: VideoCameraOutlined
      };
      return iconMap[type] || FileOutlined;
    },
    getResourceTypeName(type) {
      return this.resourceTypes[type] || '未知类型';
    },
    confirmDeleteResource() {
      Modal.confirm({
        title: '确认删除',
        content: `确定要删除资源 "${this.resource?.title}" 吗？`,
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this.$emit('delete-resource', this.resource.id);
        }
      });
    },
    confirmDeleteFile() {
      Modal.confirm({
        title: '确认删除',
        content: `确定要删除文件 "${this.selectedFile?.name}" 吗？`,
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this.$emit('delete-file', this.selectedFile.id);
        }
      });
    },
    goToChat() {
      this.$router.push('/chat');
      this.localVisible = false;
    },
    getDifyFileType(filename) {
      const extension = filename.split('.').pop().toLowerCase();
      const typeMap = {
        doc: 'document',
        docx: 'document',
        pdf: 'document',
        jpg: 'image',
        png: 'image',
        mp3: 'audio',
        mp4: 'video'
      };
      return typeMap[extension] || 'file';
    },
    async sendAnalysisWithUrl() {
      if (!this.selectedFile?.url) {
        this.$message.warning('文件URL不可用');
        return;
      }

      this.analyzing = true;
      try {
        const payload = {
          inputs: {},
          query: "请分析此文件内容",
          response_mode: "streaming",
          conversation_id: "",
          user: this.currentUser,
          files: [{
            type: "document", //this.getDifyFileType(this.selectedFile.name)
            transfer_method: "remote_url",
            url: "https://service-ciqdluo4-1321569903.gz.tencentapigw.com.cn/release/2116411031+王靖+十问题解答 .docx"
          }]
        };

        console.log('发送请求:', payload);

        const response = await axios.post(
          `${this.difyConfig.baseUrl}${this.difyConfig.endpoints.chat}`,
          payload,
          {
            headers: {
              'Authorization': `Bearer ${this.difyConfig.apiKey}`,
              'Content-Type': 'application/json'
            }
          }
        );

        this.$message.success('分析请求已发送');
        return response.data;
      } catch (error) {
        console.error('API错误:', {
          request: error.config?.data,
          response: error.response?.data
        });
        throw error;
      } finally {
        this.analyzing = false;
      }
    },
  },
  mounted() {
    if (this.selectedFile && this.selectedFile.json_data) {
      this.loadJsonData();
    }
  }
};
  </script>
